package com.aggregate.pay.transfar.support;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.transfar.support.utils.JSON;
import com.aggregate.pay.transfar.support.utils.MD5;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

/**
 * 传化接口专属工具类
 * @author Moyq5
 * @date 2018年10月24日
 */
public class Tool {
	
	private static Logger log = LoggerFactory.getLogger(Tool.class);
	

	public static Map<String, String> sign(Object data, String key) throws Exception {
		return sign(JSON.toString(data), key);
	}
	
	public static Map<String, String> sign(String json, String key) throws Exception {
		Map<String, String> map = Tool.sortFields(json);
		map.put("dog_sk", key);
		String sign = sign(map);
		map.put("tf_sign", sign);
		map.remove("dog_sk");
		return map;
	}
	
	public static Map<String, String> sortFields(String jsonString) throws JsonParseException, IOException {
		Map<String, String> fields = new TreeMap<String, String>();
		JsonFactory jsonFactory = new JsonFactory();
		JsonParser jp = jsonFactory.createParser(jsonString);
		jp.nextToken();
		while (jp.nextToken() != JsonToken.END_OBJECT) {
			String fieldName = jp.getCurrentName();
			jp.nextToken();
			fields.put(fieldName, jp.getValueAsString());
		}
		jp.close();
		return fields;
	}
	
	public static String sign(Map<String, String> map) {
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> entry: map.entrySet()) {
			if (null != entry.getValue() && !entry.getValue().isEmpty()) {
				sb.insert(0, entry.getValue());
			}
		}
		String src = sb.toString();
		log.debug("传化->签名内容：{}", src);
		String sign = MD5.MD5Encode(src).toUpperCase();
		log.debug("传化->签名值：{}", sign);
		return sign;
	}
	
}